package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //1.kafka连接配置信息
        Properties properties = new Properties();

        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");

        //消息key和value的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //生产者确认机制
        properties.put(ProducerConfig.ACKS_CONFIG,"all");

       //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);

        //消息压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"gzip");

        //2.创建kafka的生成者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3.1 封装发送的消息
        /**
         * 1 topic
         * 2 消息的key
         * 3 消息的value
         */
        ProducerRecord<String, String> record = new ProducerRecord<String, String>("topic-first", 0, "key-01", "hello kafka2");

        //3.2 发送消息

        //同步
        /*RecordMetadata recordMetadata = producer.send(record).get();
        System.out.println(recordMetadata.offset());*/

        //异步
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null) {
                    System.out.println("记录异常信息到日志表中");
                }
                System.out.println(recordMetadata.offset());
            }
        });


        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();

    }

}